<template>
  <div>
    <el-card shadow="hover" class="layout-padding-auto">
      <TableSearch
        :search="state.search"
        @search="onSearch"
        @listenClick="listenClick"
      />
      <Table
        ref="tableRef"
        v-bind="state.tableData"
        class="table-demo"
        @pageChange="onTablePageChange"
        @expandChange="expandChange"
        @listenClick="listenClick"
      >
        <template #default="{ slotData, slotColumn }">
          <div v-if="slotColumn.key === 'applyType'">
            {{
              slotData.applyType == 1
                ? '维修申请'
                : slotData.applyType == 2
                ? '维保申请'
                : '点检申请'
            }}
          </div>
          <div v-if="slotColumn.key === 'approveStatus'">
            {{
              slotData.approveStatus == 0
                ? '待提交'
                : slotData.approveStatus == 1
                ? '待审核'
                : '已审核'
            }}
          </div>
          <div v-if="slotColumn.key === 'status'">
            {{
              slotData.status == 1
                ? '待审核'
                : slotData.status == 2
                ? '不通过'
                : slotData.status == 3
                ? '已出库'
                : ''
            }}
          </div>
        </template>
      </Table>
      <ExamineOutDialog
        :outVisible="outVisible"
        :outForm="outForm"
        @cancelOut="cancelOut"
        @submitOut="submitOut"
      ></ExamineOutDialog>
      <ExamineOutNoDialog
        :btgDialog="btgDialog"
        :btgForm="btgForm"
        @quxiaoBTG="quxiaoBTG"
        @submitBTG="submitBTG"
      ></ExamineOutNoDialog>
      <ApplyDetail
        :detailVisible="detailVisible"
        :outForm="outForm"
        @closeDetail="closeDetail"
      ></ApplyDetail>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { ref, reactive, defineAsyncComponent, onMounted } from 'vue'
import {
  getInfoApi,
  devicePartGetApplyInfoApi,
  devicePartGetApplyDetailInfoApi
} from '/@/api/spare'
import { getButtonListByRoleApi } from '/@/api/publicApi'
import { Session } from '/@/utils/storage'
const menu = Session.get('menu')
const buttonCodes = ref<any>([])
const userInfo = ref(Session.get('shebei'))
const Table = defineAsyncComponent(
  () => import('/@/components/table/index.vue')
)
const TableSearch = defineAsyncComponent(
  () => import('/@/components/table/search.vue')
)
const ExamineOutDialog = defineAsyncComponent(
  () => import('./components/ExamineOutDialog.vue')
)
const ApplyDetail = defineAsyncComponent(
  () => import('./components/ApplyDetail.vue')
)
const ExamineOutNoDialog = defineAsyncComponent(
  () => import('./components/ExamineOutNoDialog.vue')
)
// 定义变量内容
const tableRef = ref<RefType>()
const state = reactive<TableDemoState>({
  tableData: {
    flash: false, // 刷新表格
    // 表头内容（必传，注意格式）
    header: [
      { key: 'applyNum', colWidth: '', title: '申请单号', type: 'text' },
      { key: 'orderNum', colWidth: '', title: '关联工单号', type: 'text' },
      { key: 'applyType', colWidth: '', title: '申请类型', type: 'slot' },
      { key: 'applyAmount', colWidth: '', title: '申请配件数量', type: 'text' },
      { key: 'applyFee', colWidth: '', title: '备件总额(元)', type: 'text' },
      { key: 'applyUserName', colWidth: '', title: '申请人', type: 'text' },
      { key: 'dealUserName', colWidth: '', title: '审核人', type: 'text' },
      { key: 'createTime', colWidth: '', title: '申请时间', type: 'text' },
      { key: 'approveStatus', colWidth: '', title: '审核状态', type: 'slot' }
      // { key: 'image', colWidth: '', width: '70', height: '40', title: '图片描述', type: 'image' },
    ],
    columnBtn: [
      {
        name: 'detail',
        text: '详情',
        hide(row: any): boolean {
          return row.approveStatus == 2
        },
        type: 'primary',
        loading: false,
        btns: buttonCodes.value,
        btnCode: 'applayDetailBtn'
      },
      {
        name: 'allOut',
        text: '全部出库',
        hide(row: any): boolean {
          return (
            row.approveStatus == 1 &&
            row.dealUserName == userInfo.value.realName
          )
        },
        type: 'primary',
        loading: false,
        btns: buttonCodes.value,
        btnCode: 'applyOutBtn'
      },
      {
        name: 'allPass',
        text: '全部不通过',
        hide(row: any): boolean {
          return (
            row.approveStatus == 1 &&
            row.dealUserName == userInfo.value.realName
          )
        },
        type: 'danger',
        loading: false,
        btns: buttonCodes.value,
        btnCode: 'applyNoOutBtn'
      }
    ],
    // 配置项（必传）
    config: {
      listApi: '/device/mobile/devicePartApply/pageList',
      listHttp: 'post',
      total: 0, // 列表总数
      loading: true, // loading 加载
      noPage: false, // 是否分页
      isSerialNo: true, // 是否显示表格序号
      isSelection: false, // 是否显示表格多选
      isOperate: true, // 是否显示表格操作栏
      isExtend: true, // 是否可以扩展
      operateWidth: 300
    },
    // 搜索参数
    param: {
      // 必传参数，分页的不要传
    },
    extendTable: {
      // 二级表格
      header: [
        { key: 'partNum', colWidth: '', title: '备件编号', type: 'text' },
        { key: 'partName', colWidth: '', title: '备件名称', type: 'text' },
        { key: 'partTypeName', colWidth: '', title: '备件类型', type: 'text' },
        { key: 'amount', colWidth: '', title: '申请数量', type: 'text' },
        {
          key: 'factAmount',
          colWidth: '',
          title: '实际出库数量',
          type: 'text'
        },
        { key: 'status', colWidth: '', title: '操作状态', type: 'slot' }
      ], // 第二级的头部
      dataProp: 'partDetailResponses', // 第二级的数据字段
      isOperate: true, // 是否显示表格操作栏
      extendBtn: [
        {
          name: 'outKu',
          text: '出库',
          hide(row: any): boolean {
            return (
              row.status == '1' &&
              oneRow.value.dealUserName == userInfo.value.realName
            )
          },
          type: 'primary',
          btns: buttonCodes.value,
          btnCode: 'applyOutBtn'
        },
        {
          name: 'pass',
          text: '不通过',
          hide(row: any): boolean {
            return (
              row.status == '1' &&
              oneRow.value.dealUserName == userInfo.value.realName
            )
          },
          type: 'danger',
          btns: buttonCodes.value,
          btnCode: 'applyNoOutBtn'
        }
      ]
    }
  },
  // 搜索表单，动态生成（传空数组时，将不显示搜索，注意格式）
  search: {
    param: [
      {
        label: '',
        prop: 'keyword',
        placeholder: '输入申请单号/工单号/人名搜索',
        type: 'input'
      },
      {
        label: '审核状态',
        prop: 'approveStatus',
        placeholder: '请选择审核状态',
        options: [
          { id: 1, configValue: '待审核' },
          { id: 2, configValue: '已审核' }
        ],
        type: 'select'
      }
    ],
    btn: [
      // { text: '新增计划', fun: 'addPlan', disable: false, loading: false, type: 'primary', hide(): boolean { return false } },
      // { text: '批量生产任务', fun: 'batchImportDevice', disable: false, loading: false, type: 'primary', hide(): boolean { return false } },
    ],
    reset: true
  }
})

// 初始化列表数据
const getTableData = () => {
  state.tableData.flash = !state.tableData.flash
}
// 搜索点击时表单回调
const onSearch = (data: EmptyObjectType) => {
  state.tableData.param = Object.assign({}, state.tableData.param, { ...data })
  // console.log(state.tableData.param);
  state.tableData.flash = !state.tableData.flash
}
// 分页改变时回调
const onTablePageChange = (page: TableDemoPageType) => {
  state.tableData.param.pageNum = page.pageNum
  state.tableData.param.pageSize = page.pageSize
  getTableData()
}
//二级表格展开回调
const oneRow = ref<any>({})
const expandChange = (row: any) => {
  oneRow.value = row
}

const outVisible = ref(false)
const detailVisible = ref(false)
const outForm = ref({
  form: <any>[],
  id: '',
  type: ''
})

const allOut = (row: any) => {
  outForm.value.form = []
  devicePartGetApplyInfoApi(row.id).then((res) => {
    if (res.code == 0) {
      res.data.partDetailResponses.forEach((item: any) => {
        if (item.approveStatus == 1) {
          outForm.value.form.push(item)
        }
      })
      outForm.value.id = row.id
      outForm.value.type = '1'
      outVisible.value = !outVisible.value
    }
  })
}

const outKu = (row: any) => {
  outForm.value.form = []
  devicePartGetApplyDetailInfoApi(row.applyDetailId).then((res) => {
    if (res.code == 0) {
      outForm.value.form.push(res.data)
      outForm.value.id = row.applyDetailId
      outForm.value.type = '2'
      outVisible.value = !outVisible.value
    }
  })
}

const cancelOut = () => {
  outVisible.value = !outVisible.value
}
const submitOut = () => {
  outVisible.value = !outVisible.value
  getTableData()
}
const closeDetail = () => {
  detailVisible.value = !detailVisible.value
}

const detail = (row: any) => {
  getInfoApi(row.id).then((res) => {
    if (res.code == 0) {
      outForm.value.form = res.data
      outForm.value.id = row.id
      detailVisible.value = !detailVisible.value
    }
  })
}

const btgDialog = ref(false)
const btgForm = ref({
  type: '',
  id: ''
})
const allPass = (row: any) => {
  btgForm.value.type = '1'
  btgForm.value.id = row.id
  btgDialog.value = !btgDialog.value
}

const pass = (row: any) => {
  btgForm.value.type = '2'
  btgForm.value.id = row.applyDetailId
  btgDialog.value = !btgDialog.value
}

const quxiaoBTG = () => {
  btgDialog.value = !btgDialog.value
}
const submitBTG = () => {
  btgDialog.value = !btgDialog.value
  getTableData()
}

//定义方法对象 注意定义的方法 必须在上面已经申明 所以建议objFun申明和 listenClick方法 写在页面最下面
const objFun = {
  allOut: allOut,
  detail: detail,
  outKu: outKu,
  allPass: allPass,
  pass: pass
}
// 监听子级表格  传过来的方法
const listenClick = (name: string, val: any) => {
  objFun[name](val)
}

onMounted(() => {
  menu.forEach(async (element: any) => {
    if (element.menuUrl == '/spare/apply') {
      let res = await getButtonListByRoleApi({
        terminalType: 1,
        menuPid: element.id
      })
      res.data.forEach((item: any) => {
        buttonCodes.value.push(item.buttonCode)
      })
    }
  })
})
</script>
<style scoped lang="scss"></style>
